/* 
 * Created on 2007-5-27
 * Last modified on 2011-11-3
 * Powered by YeQiangWei.com
 */
package com.fadadianqi.search;

import com.fadadianqi.commons.Constants;
import com.yeqiangwei.commons.io.FileHelper;
import com.yeqiangwei.commons.util.StringHelper;
import com.yeqiangwei.commons.util.Utils;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.thesaurus.AnalyzerUtils;
import org.apache.lucene.analysis.thesaurus.WordTreeFactory;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.TermVector;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchUtils {

    private static Logger logger = Logger.getLogger(SearchUtils.class);

    private static Analyzer analyzer;

    private static Map<String, String> big5; // 繁简转换表

    static {
        if (analyzer == null) {
            analyzer = AnalyzerFactory.getInstance();
        }
    }

    public static void main(String args[]) throws IOException {
        // SearchUtils.filterKeys("張學友");
        WordTreeFactory.setWordPath("/opt/www/yqw-main/WebRoot/WEB-INF/conf/index/word.txt");
        WordTreeFactory.getInstance();
        System.out.println(SearchUtils.optimizeChineseKeywords("爱就一个字"));
    }

    public static String optimizeChineseKeywords(String q) {
        StringBuilder keys = new StringBuilder();
        org.apache.lucene.analysis.Token[] tokens;
        try {
            /*
			 * 分解关键词
			 */
            tokens = AnalyzerUtils.tokensFromAnalysis(SearchUtils.getAnalyzer(), q);
            if (!ValidatorHelper.isEmpty(tokens)) {
                for (int i = 0; i < tokens.length; i++) {
                    String temp = tokens[i].term();
                    if (!temp.equals(q) && temp.length() >= 2) {
                        keys.append(temp);
                        if (i > 5 || i == temp.length() - 1) {
                            break;
                        } else {
                            keys.append(" ");
                        }
                    }
                }
            }
        } catch (IOException e) {
            logger.error(e.toString());
        }
        if (!ValidatorHelper.isEmpty(keys) && !q.equals(keys.toString())) {
            keys.insert(0, q + " ");
        } else {
            keys.insert(0, q);
        }
        return keys.toString();
    }

    /**
     * 关键字过滤 繁体转简体 英文＋AND
     *
     * @param str
     * @return
     */
    public static String filterKeys(String keyword) {
        if (ValidatorHelper.isEmpty(keyword)) {
            return keyword;
        }
        if (keyword.length() > 50) {
            keyword = StringHelper.substring(keyword, 0, 50, keyword);
        }
        try {
            if (ValidatorHelper.isEmpty(big5)) {
                File root = new File(Constants.ROOT_PATH);
                File dir = FileHelper.findDirectory(root, "WEB-INF");
                if (dir == null) {
                    return keyword;
                }
                String path = dir.getAbsolutePath() + File.separator + "index" + File.separator + "big5.txt";
                logger.info("big5: " + path);
                big5 = new HashMap<String, String>();
                String temp = FileHelper.readText(path, "utf-8").replace("\r", "").replace("\n", "");
                big5 = new HashMap<String, String>();
                if (!ValidatorHelper.isEmpty(temp)) {
                    String jianti = StringHelper.substring(temp, 0, temp.indexOf("|"), temp).trim();
                    String fanti = StringHelper.substring(temp, temp.indexOf("|") + 1, temp.length(), temp).trim();
                    char[] chars_jianti = jianti.toCharArray();
                    char[] chars_fanti = fanti.toCharArray();
                    for (int i = 0; i < chars_fanti.length; i++) {
                        big5.put(String.valueOf(chars_fanti[i]), String.valueOf(chars_jianti[i]));
                    }
                }
            }
            char[] chars = keyword.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                String word = String.valueOf(chars[i]);
                if (ValidatorHelper.isEmpty(word)) {
                    continue;
                }
                String big5w = big5.get(word);
                if (ValidatorHelper.isEmpty(big5w)) {
                    continue;
                }
                keyword = keyword.replace(word, big5w);
            }

        } catch (IOException e) {
            logger.error(e.toString());
        }
        return keyword;
    }

    /**
     * @param word
     * @return
     */
    public static boolean charIsLetter(String word) {
        boolean sign = true; // 初始化标志为为'true'
        for (int i = 0; i < word.length(); i++) { // 遍历输入字符串的每一个字符
			/*
			 * if (!Character.isLetter(word.charAt(i)) &&
			 * !String.valueOf(word.charAt(i)).equals(" ")) { // 判断该字符是否为英文字符
			 * sign = false; // 若有一位不是英文字符，则将标志位修改为'false' }
			 */
            String tmp = String.valueOf(word.charAt(i));
            if (!Utils.isLetter(tmp) && !tmp.equals(" ")) {
                sign = false; // 若有一位不是英文字符，则将标志位修改为'false'
            }
        }
        return sign; // 返回标志位结果
    }


    public static Analyzer getAnalyzer() {
        return analyzer;
    }

    public static Directory getDirectory(File file) throws IOException {
        FSDirectory directory = FSDirectory.open(file, null);
        return directory;
    }

    public static Directory getDirectory(String path) throws IOException {
        return getDirectory(new File(path));
    }

    public static Directory unlock(String indexfolder) throws IOException {
        Directory directory = getDirectory(indexfolder);
        if (IndexWriter.isLocked(directory)) {
            IndexWriter.unlock(directory);
        }
        return directory;
    }

    public static IndexWriter getIndexWriter(String indexfolder) throws IOException {
        Directory directory = unlock(indexfolder);
        IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_34, getAnalyzer());
        return new IndexWriter(directory, config);
    }


    public static Index UN_TOKENIZED = Field.Index.NOT_ANALYZED;

    public static final Field text(String name, String value, Index index) {
        TermVector termVector = Field.TermVector.WITH_POSITIONS_OFFSETS;
        return new Field(name, value, Field.Store.YES, index,
                termVector);
    }

    public static final Field text(String name, String value) {
        if (name == null || value == null) {
            return null;
        }
        TermVector termVector = Field.TermVector.WITH_POSITIONS_OFFSETS;
        return new Field(name, value, Field.Store.YES, Field.Index.ANALYZED,
                termVector);
    }

    public static final Field text(String name, int value, Index index) {
        TermVector termVector = Field.TermVector.WITH_POSITIONS_OFFSETS;
        return new Field(name, String.valueOf(value), Field.Store.YES, index,
                termVector);
    }

    public static final Field text(String name, int value) {
        TermVector termVector = Field.TermVector.WITH_POSITIONS_OFFSETS;
        return new Field(name, String.valueOf(value), Field.Store.YES,
                Field.Index.ANALYZED, termVector);
    }

    public static final Field text(String name, long value, Index index) {
        TermVector termVector = Field.TermVector.WITH_POSITIONS_OFFSETS;
        return new Field(name, String.valueOf(value), Field.Store.YES, index,
                termVector);
    }

    public static final Field text(String name, long value) {
        TermVector termVector = Field.TermVector.WITH_POSITIONS_OFFSETS;
        return new Field(name, String.valueOf(value), Field.Store.YES,
                Field.Index.ANALYZED, termVector);
    }

    public static void delete(List<Term> terms, String indexPath) throws IOException {
        if (null == terms) {
            return;
        }
        Directory directory = SearchUtils.getDirectory(indexPath);
        IndexReader reader = IndexReader.open(directory, Boolean.FALSE);
        if (IndexWriter.isLocked(directory)) {
            IndexWriter.unlock(directory);
        }
        for (int i = 0; i < terms.size(); i++) {
            Term aTerm = terms.get(i);
            if (null != aTerm) {
                reader.deleteDocuments(aTerm);
            }
        }
        try {
            if (null != reader) {
                reader.flush();
                reader.close();
            }
            directory.close();
        } catch (RuntimeException e) {
            logger.error(e);
        }
    }

    /**
     * 执行索引删除
     *
     * @param id        编号
     * @param idname    ID名称
     * @param indexpath 索引目录
     * @throws IOException
     */
    public static void delete(Object id, String idname, String indexPath) throws IOException {
        Term aTerm = new Term(idname, String.valueOf(id));
        indexTermList(aTerm, indexPath);
    }

    public static void indexTermList(Term aTerm, String indexPath) throws IOException {
        List<Term> aList = new ArrayList<Term>();
        aList.add(aTerm);
        delete(aList, indexPath);
    }
}
